﻿var page = {
    pagetotal: 0,
    pageSize: 10,
    pageNumber: 1,
    rootPath: getRootPath(), //网站根路径
    commonUrl: getRootPath() + "/Ashx/CommonHandler.ashx",
    ajaxUrl: getRootPath() + "/Ashx/ApsHandler/ScheduledTaskHandler.ashx",
    ajaxUrlAps: getRootPath() + "/Ashx/ApsHandler/ApsLimitedCapacityHandler.ashx",
    //初始化页面
    init: function () {
        page.bind();
        page.loadFactory();
        customizedEasyuiPagination('pp'); //定制化分页
        page.addEditCell();
        //page.openTaskForm();
    },
    addEditCell: function () //给easyuigrid新增editcell方法
    {
        $.extend($.fn.datagrid.methods, {
            editCell: function (jq, param) {
                return jq.each(function () {
                    var opts = $(this).datagrid('options');
                    var fields = $(this).datagrid('getColumnFields', true).concat($(this).datagrid('getColumnFields'));
                    for (var i = 0; i < fields.length; i++) {
                        var col = $(this).datagrid('getColumnOption', fields[i]);
                        col.editor1 = col.editor;
                        if (fields[i] != param.field) {
                            col.editor = null;
                        }
                    }
                    $(this).datagrid('beginEdit', param.index);
                    for (var i = 0; i < fields.length; i++) {
                        var col = $(this).datagrid('getColumnOption', fields[i]);
                        col.editor = col.editor1;
                    }
                });
            }
        });
    },
    endEditing: function (gridId) {
        if (page.editIndex == undefined) { return true }
        if ($('#' + gridId).datagrid('validateRow', page.editIndex)) {
            $('#' + gridId).datagrid('endEdit', page.editIndex);
            page.editIndex = undefined;
            return true;
        } else {
            return false;
        }
    },
    //页面事件绑定
    bind: function () {
        //grid初始化
        $("#gdScheduledTask").datagrid({
            onLoadSuccess: function (data) {
                $('#pp').pagination('refresh', {	// 改变选项，并刷新分页栏信息
                    total: page.pagetotal,
                    pageSize: page.pageSize,
                    pageNumber: parseInt(page.pageNumber)
                });
                customizedEasyuiPagination('pp'); //定制化分页

            },
            onSelect: function (index, rowData) {
                page.reset(false, false, true);
                page.loadScheduledTaskLog(rowData.SCHEDULEDTASKID);
            },
            onCheck: function (index, rowData) {
                page.reset(false, false, true);

            },
            onUncheck: function (index, rowData) {
                page.reset(false, false, true);
            },
            onCheckAll: function (index, rowData) {
                page.reset(false, false, true);
            },
            onUncheckAll: function (index, rowData) {
                page.reset(false, false, true);
            },
            onClickCell: function (index, field) {
                //编辑单元格
                if (page.endEditing('gdScheduledTask')) {
                    $('#gdScheduledTask').datagrid('editCell', { index: index, field: field });
                    page.editIndex = index;
                }
                return false;
            },
            columns: [[
                 { field: 'ck', title: '选择', checkbox: true, hidden: true },
                 { field: 'TASKNAME', title: '任务名称', width: 120 },
		         { field: 'TASKDESC', title: '任务描述', width: 180 },
		         { field: 'STATUS', title: '运行状态', width: 80, formatter: function (value, row, index) {
		             if (value == "1") {
		                 return "待执行";
		             } else if (value == "2") {
		                 return "执行中";
		             } else if (value == "3") {
		                 return "错误";
		             } else {
		                 return value;
		             }
		         }
		         },
                 { field: 'CYCLETIME', title: '重复周期(天)', width: 120 },
                 { field: 'LASTEXCUTIME', title: '上次运行时间', width: 120 },
                 { field: 'NEXTEXCUTIME', title: '下次运行时间', width: 120, editor: { type: 'datetimebox' }, formatter: function (value, row, index) {
                     if (value != null) {
                         return dayjs(value).format("YYYY-MM-DD HH:mm:ss");
                     }
                 }
                 },
                 { field: 'CREATENAME', title: '创建人', width: 80 },
                 { field: 'CREATEDATE', title: '创建时间', width: 120 },
                 { field: 'LASTCHANGENAME', title: '修改人', width: 80 },
                 { field: 'LASTCHANGEDATE', title: '修改时间', width: 120 }

	           ]],
            onAfterEdit: function (index, row, change) {

                if (change.NEXTEXCUTIME != null)//手动更改下次运行日期
                {
                    page.saveManualNextDate(row);
                }
            }

        });
        $("#dgScheduledTaskLog").datagrid({
            onLoadSuccess: function (data) {

            },
            columns: [[
                 { field: 'EXECUTETYPE', title: '执行类型', width: 80, formatter: function (value, row, index) {
                     if (value == "1") { return "自动"; }
                     else if (value == "2") { return "手动"; }
                     else { return value; }
                 }
                 },
		         { field: 'STATUS', title: '运行状态', width: 80, formatter: function (value, row, index) {
		             if (value == "4") {
		                 return "已完成";
		             } else if (value == "2") {
		                 return "执行中";
		             } else if (value == "3") {
		                 return "错误";
		             } else {
		                 return value;
		             }
		         }
		         },
                 { field: 'TASKEXESTARTTIME', title: '任务开始时间', width: 150 },
                 { field: 'DURATION', title: '持续时长', width: 100, formatter: function (value, row, index) {
                     if (!isNullOrWhiteSpaceStr(row.TASKEXESTARTTIME) && !isNullOrWhiteSpaceStr(row.TASKEXEENDTIME)) {
                         var diffMin = dayjs(row.TASKEXEENDTIME).diff(dayjs(row.TASKEXESTARTTIME), 'minute', true);
                         var re = '';
                         re = re + Math.floor(diffMin / 60).toString() + 'H' + Math.round(diffMin % 60).toString() + 'MIN';
                         return re;
                     }
                 }
                 },
                 { field: 'TASKEXEENDTIME', title: '任务结束时间', width: 150 },
                 { field: 'LOGMESSAGE', title: '日志描述', width: 500, formatter: function (value, row, index) {
                     if (isNullOrWhiteSpaceStr(value)) {
                         return value;
                     }
                     var v = value.replace(/[\r\n]/g, "");
                     //prompt("",v);
                     return '<span title=' + v.replace(/[ ]/g, "") + '>' + v + '</span>'
                 }
                 }

	           ]]

        });
        //操作日志表
        $("#operaLogTable").datagrid({
            columns: [[
                 { field: 'TASKNAME', title: '任务名', width: 120 },
		         { field: 'FULLNAME', title: '操作者', width: 80 },
                 { field: 'OPERATIONDATE', title: '操作时间', width: 150, formatter: function (value, row, index) {
                     return dayjs(value).format('YYYY-MM-DD HH:mm:ss');
                 }
                 },
                 { field: 'NOTES', title: '操作日志', width: 350 }
	           ]]

        });
        //排产定时任务取消保存
        $('#popTaskCancel').on("click", function () {
            clearMessage();
            $('#dg').dialog('close');
        });
        //查询
        $('#btnSearch').on("click", function () {
            page.reset(false, true, true);
            page.pageNumber = 1;
            page.searchData();
        });
        //新增按钮
        //        $('#btnAddTask').on("click", function () {
        //            page.openTaskForm(1, false);
        //        });
        //自动排产新增按钮
        $('#addApsTask').on("click", function () {
            page.openTaskForm(1, false);
        });
        //自动开卡新增按钮 add by zhangrj 20240109
        $('#addAutoStartTask').on("click", function () {
            page.openTaskForm(2, false);
        });
        //自动预排产新增按钮 add by zhangrj 20250113
        $('#addTryApsTask').on("click", function () {
            page.openTaskForm(8, false);
        });
        //自动排产转工接收新增按钮 add by zhangrj 20251106
        $('#addApsShipReceive').on("click", function () {
            page.openTaskForm(9, false);
        });
        //编辑按钮
        $('#btnEditTask').on("click", function () {
            page.openTaskForm(0, true);
        });
        //手工停止
        $('#btnManualTaskStop').on("click", function () {
            page.manualScheduledTaskStop();
        });
        //手工开始
        $('#btnManualTaskStart').on("click", function () {
            page.manualScheduledTaskStart();
        });
        //删除按钮
        $('#btnDelTask').on("click", function () {
            $.messager.confirm('确认', '确定要删除吗？', function (flag) {
                if (flag) {
                    page.deleteApsScheduledTask();
                }
            });

        });
        //操作日志按钮
        $('#btnOperaDetail').on("click", function () {
            page.loadLogData();
        });
        //分页事件
        $('#pp').pagination({
            onSelectPage: function (pageNumber, pageSize) {
                customizedEasyuiPagination('pp'); //定制化分页
                page.pageSize = pageSize; page.pageNumber = pageNumber;
                page.searchData();
            }
        });
        //绑定分页go按钮
        $('#pageGo').on("click", function () {
            var pageNumber = $(this).parents('tr').find('.pagination-num').val();
            page.pageNumber = pageNumber;
            page.searchData();
        });
        //清除按钮
        $('#btnReset').on("click", function () {
            page.reset(true, true);
            page.pageNumber = 1; page.pagetotal = 0
            $('#pp').pagination('refresh', {
                total: page.pagetotal,
                pageSize: page.pageSize,
                pageNumber: page.pageNumber
            });
        })
    },
    //分厂下拉初始化
    loadFactory: function () {
        $.ajax({
            type: "Post",
            url: getRootPath() + "/Ashx/CommonHandler.ashx?action=getFactory",
            data: {},
            cashe: false,
            async: true,
            beforeSend: function () {
            },
            success: function (data) {
                var result = JSON.parse(data);
                $('#ddlFactory').combobox({
                    data: result,
                    valueField: 'FACTORYID',
                    textField: 'FACTORYNAME',
                    value: result[0].FACTORYID, //默认值   
                    onSelect: function (record) {
                        page.reset(false, true, true);
                    }
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            }
        });
    },
    //查询
    searchData: function () {
        var gridID = "#gdScheduledTask";
        var param = {
            action: "searchSTData",
            pageSize: page.pageSize,
            pageNumber: page.pageNumber,
            factoryId: $("#ddlFactory").combobox('getValue')
        };
        if (isNullOrWhiteSpaceStr(param.factoryId)) {
            displayMessage("无效分厂", false);
            return;
        }
        //console.log(param);
        $.ajax({
            type: "Post",
            url: page.ajaxUrl,
            data: param,
            cashe: false,
            async: true,
            beforeSend: function () {
                $(gridID).datagrid('loading');
                $(this).attr("disabled", "disabled"); //禁用按钮
            },
            success: function (data) {
                //console.log(data);
                $(gridID).datagrid('loaded');
                $(this).removeAttr("disabled"); //恢复按钮
                var result = JSON.parse(data);
                //console.log(result);
                if (result.Result) {
                    //给分页对象赋值
                    page.pagetotal = result.RowCount;
                    $(gridID).datagrid('loadData', { total: result.RowCount, rows: result.DBTable });
                } else {
                    displayMessage(result.Message, false);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $(gridID).datagrid('loaded');
                $(this).removeAttr("disabled"); //恢复按钮
                alert(XMLHttpRequest.responseText);
            }
        });
    },
    //打开弹窗 add by zhangrj 20231031
    openDialog: function (height, width) {
        $('#dg').dialog({
            title: '定时任务维护',
            fit: false,
            top: 10,
            width: width,
            height: height,
            closed: false,
            cache: false,
            modal: true,
            returnData: null,
            popupData: null,
            onClose: function () {
                var re = $("#dg").dialog('options').returnData;
                if (re != null) {
                    if (re.Result) {
                        page.searchData();
                    }
                }
                page.resetDialog();
            }
        });
    },
    //打开定时任务弹出框（统一的弹窗入口，type：即为定时任务类型（添加类型时，一定要先看字典用了多少类型，然后再添加），isEdit：是否编辑） add by zhangrj 20231031
    openTaskForm: function (type, isEdit) {
        var popupData = { factoryId: $('#ddlFactory').combobox('getValue'), selectRow: null };
        if (isEdit) {
            var selectRow = $("#gdScheduledTask").datagrid('getSelected');
            popupData.selectRow = selectRow;
            if (selectRow == null) {
                displayMessage("请选择记录", false);
                return;
            }
            //执行中状态不能编辑
            if (selectRow.STATUS == '2') {
                displayMessage("执行中状态不能编辑", false);
                return;
            }
            type = selectRow.TASKTYPE;
        }
        $("#popddlTaskName").combobox('disable');
        //添加类型时，一定要先看字典用了多少类型，然后再添加，比如热表定时任务添加用了3——7的了
        switch (type) {
            case 1: //自动排产任务
                apsTask.initForm(popupData);
                page.openDialog(400, 570); //打开弹窗
                break;
            case 2: //自动开卡任务
                autoStartTask.initForm(popupData);
                page.openDialog(300, 570); //打开弹窗
                break;
            case 8: //自动预排产任务
                tryApsTask.initForm(popupData);
                page.openDialog(350, 570); //打开弹窗
                break;
            case 9: //自动排产转工接收
                shipApsRecTask.initForm(popupData);
                page.openDialog(350, 550); //打开弹窗
                break;
            default:

        }
    },
    //删除排产定时任务信息
    deleteApsScheduledTask: function () {
        var selectRow = $("#gdScheduledTask").datagrid('getSelected');
        if (selectRow == null) {
            displayMessage("请选择记录", false);
            return;
        }
        //执行中状态不能编辑
        if (selectRow.STATUS == '2') {
            displayMessage("执行中状态不能删除", false);
            return;
        }
        //开始请求后台
        $.ajax({
            type: "Post",
            url: page.ajaxUrl,
            data: { action: "deleteApsScheduledTask", scheduledtaskid: selectRow.SCHEDULEDTASKID },
            cashe: false,
            async: true,
            beforeSend: function () {
                $.messager.progress({ text: '', msg: '处理中...' });
            },
            success: function (data) {
                //console.log(data);
                $.messager.progress('close');
                var result = JSON.parse(data);
                if (result.Result) {
                    displayMessage("删除成功", true);
                    page.searchData();
                } else {
                    displayMessage(result.Message, false);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $.messager.progress('close');
                alert(XMLHttpRequest.responseText);
            }
        });

    },
    //加载定时任务日志
    loadScheduledTaskLog: function (id) {
        var gridID = "#dgScheduledTaskLog";
        var param = {
            action: "loadScheduledTaskLog",
            scheduledtaskid: id
        };
        //console.log(param);
        $.ajax({
            type: "Post",
            url: page.ajaxUrl,
            data: param,
            cashe: false,
            async: true,
            beforeSend: function () {
                $(gridID).datagrid('loading');
            },
            success: function (data) {
                //console.log(data);
                $(gridID).datagrid('loaded');
                var result = JSON.parse(data);
                //console.log(result);
                if (result.Result) {
                    $(gridID).datagrid('loadData', { total: result.RowCount, rows: result.DBTable });
                } else {
                    displayMessage(result.Message, false);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $(gridID).datagrid('loaded');
                alert(XMLHttpRequest.responseText);
            }
        });
    },
    //手工开始
    manualScheduledTaskStart: function () {
        var selectRow = $("#gdScheduledTask").datagrid('getSelected');
        if (selectRow == null) {
            displayMessage("请选择记录", false);
            return;
        }
        //执行中状态不能编辑
        if (!(selectRow.STATUS == '1' || selectRow.STATUS == '3')) {
            displayMessage("只能开始待执行或错误状态的任务", false);
            return;
        }
        var param = { action: "manualScheduledTask", scheduledtaskid: selectRow.SCHEDULEDTASKID, manualtype: 1 };

        $.ajax({
            type: "Post",
            url: page.ajaxUrl,
            data: param,
            cashe: false,
            async: true,
            beforeSend: function () {
                $.messager.progress({ text: '', msg: '处理中...' });
            },
            success: function (data) {
                //console.log(data);
                $.messager.progress('close');
                var result = JSON.parse(data);
                //console.log(result);
                if (result.Result) {
                    page.reset(false, true, true);
                    displayMessage("执行成功", true);
                    page.searchData();
                } else {
                    displayMessage(result.Message, false);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $.messager.progress('close');
                alert(XMLHttpRequest.responseText);
            }
        });
    },
    //手工停止
    manualScheduledTaskStop: function () {
        var selectRow = $("#gdScheduledTask").datagrid('getSelected');
        if (selectRow == null) {
            displayMessage("请选择记录", false);
            return;
        }
        //执行中状态不能编辑
        if (selectRow.STATUS != '2') {
            displayMessage("只能停止执行中状态的任务", false);
            return;
        }
        var param = { action: "manualScheduledTask", scheduledtaskid: selectRow.SCHEDULEDTASKID, manualtype: 2 };

        $.ajax({
            type: "Post",
            url: page.ajaxUrl,
            data: param,
            cashe: false,
            async: true,
            beforeSend: function () {
                $.messager.progress({ text: '', msg: '处理中...' });
            },
            success: function (data) {
                //console.log(data);
                $.messager.progress('close');
                var result = JSON.parse(data);
                //console.log(result);
                if (result.Result) {
                    page.reset(false, true, true);
                    displayMessage("执行成功", true);
                    page.searchData();
                } else {
                    displayMessage(result.Message, false);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $.messager.progress('close');
                alert(XMLHttpRequest.responseText);
            }
        });
    },
    //打开操作日志
    loadLogData: function () {
        page.post(page.ajaxUrl, { action: "GetScheduledTaskOperaLog", factoryId: $("#ddlFactory").combobox('getValue') }, true, function (res) {
            if (res.Result) {
                $('#dgOperaLog').dialog({
                    title: '操作日志',
                    top: 50,
                    width: '700px',
                    height: '500px',
                    closed: false,
                    cache: false,
                    modal: true,
                    buttons: [{
                        text: '关闭',
                        handler: function () { $('#dgOperaLog').dialog('close'); }
                    }]
                });
                $("#operaLogTable").datagrid('loadData', res.DBTable);
            }
        });
    },
    //清除方法，重要！！！
    reset: function (iscondition, isresult, isdetail) {
        clearMessage();
        if (iscondition) {

        }
        if (isresult) {
            clearEasyuiDataGrid("gdScheduledTask");
        }
        if (isdetail) {
            clearEasyuiDataGrid("dgScheduledTaskLog");
        }
    },
    //清空弹窗数据 add by zhangrj 20231031
    resetDialog: function () {
        //自动排产
        $("#popddlTaskName").combobox('clear');
        $("#poptxtStartDate").datetimebox('clear');
        $('#poptxtEndDate').datebox('clear');
        $("#poptxtTaskDesc").textbox('clear');
        $("#txtCycle").numberbox('clear');
        $("#cxIsCalPriority").checkbox('uncheck');
        $("#poptxtFactory").textbox('clear');
        //自动开卡
        $("#batchProcessRule").textbox('clear');
        $("#singleCardRule1").textbox('clear');
        $("#singleCardRule2").textbox('clear');
        $("#batchChildRule1").textbox('clear');
        $("#batchChildRule2").textbox('clear');
        //自动预排产
        $("#popddlTryApsPool").combobox('clear');
        //自动排产转工接收
        $("#asReceiveRefer").combobox('clear');
        $("#asRevCoverCycle").textbox('clear');
    },
    //POST数据 add by zhangrj 20231031
    post: function (url, params, async, successCallback, errorCallback) {
        $.ajax({
            type: "Post",
            url: url,
            data: params,
            cashe: false,
            async: async,
            dataType: "json",
            beforeSend: function () {
                $.messager.progress({ text: '', msg: '处理中...' });
            },
            success: function (result) {
                $.messager.progress('close');
                successCallback(result);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $.messager.progress('close');
                displayMessage(XMLHttpRequest.responseText, false);
                if (errorCallback !== undefined) {
                    errorCallback();
                }
            }
        });
    },
    //手动修改下次执行时间
    saveManualNextDate: function (row) {
        clearMessage();
        $('#gdScheduledTask').datagrid('acceptChanges');
        var postData = {
            action: "saveManualNextDate",
            scheduledTaskId: row.SCHEDULEDTASKID,
            nextExcuTime: row.NEXTEXCUTIME
        }

        $.ajax({
            type: "Post",
            url: page.ajaxUrl,
            data: postData,
            cashe: false,
            async: true,
            beforeSend: function () {
                $.messager.progress({ text: '', msg: '处理中...' });
            },
            success: function (data) {
                //console.log(data);
                $.messager.progress('close');
                var result = JSON.parse(data);
                //console.log(result);
                if (result.Result) {
                    page.reset(false, true, true);
                    displayMessage("保存成功", true);
                    page.searchData();
                } else {
                    displayMessage(result.Message, false);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $.messager.progress('close');
                alert(XMLHttpRequest.responseText);
            }
        });

    }

};

/*
----排产任务弹窗对象 edit by zhangrj 20231031
*/
var apsTask = {
    selectRow: null,
    //初始化弹窗页面
    initForm: function (popupData) {
        apsTask.selectRow = popupData.selectRow;
        apsTask.showContent(); //显示页面内容
        apsTask.bind();
        if (apsTask.selectRow !== null) {
            page.post(page.ajaxUrl, { action: "GetScheduledTaskDetailData", taskType: apsTask.selectRow.TASKTYPE, scheduledTaskId: apsTask.selectRow.SCHEDULEDTASKID }, false, function (result) {
                if (result.Result) {
                    $("#popddlTaskName").combobox('setValue', apsTask.selectRow.TASKTYPE);
                    $("#poptxtStartDate").datetimebox('setValue', apsTask.selectRow.TASKSTARTTIME);
                    $("#poptxtEndDate").datetimebox('setValue', apsTask.selectRow.TASKENDTIME);
                    $("#poptxtTaskDesc").textbox('setValue', apsTask.selectRow.TASKDESC);
                    $("#txtCycle").numberbox('setValue', apsTask.selectRow.CYCLETIME);
                    apsTask.selectRow.APSPOOLID = result.DBTable[0].APSPOOLID;
                    if (result.DBTable[0].ISCALPRIORITY == "1") {
                        $("#cxIsCalPriority").checkbox('check');
                    } else {
                        $("#cxIsCalPriority").checkbox('uncheck');
                    }
                    if (result.DBTable[0].ISAPSTOEMP == "1") {
                        $("#cxIsApsToEmp").checkbox('check');
                    } else {
                        $("#cxIsApsToEmp").checkbox('uncheck');
                    }
                } else {
                    displayMessage(result.Message, false);
                    $('#dg').dialog('close');
                    return;
                }
            }, function () {
                $('#dg').dialog('close');
                return;
            });
        } else {
            $("#popddlTaskName").combobox('setValue', '1');
            $("#cxIsCalPriority").checkbox('check');
            $("#cxIsApsToEmp").checkbox('check');
        }
        $("#poptxtFactory").textbox('setValue', $("#ddlFactory").combobox('getText'));
        $('#popddlApsPool').combobox({
            url: page.ajaxUrl + "?action=getPoolList&factoryId=" + popupData.factoryId,
            valueField: 'APSPOOLID',
            textField: 'APSPOOLNAME',
            onLoadSuccess: function () {
                if (apsTask.selectRow != null && apsTask.selectRow.APSPOOLID != null) {
                    $(this).combobox('setValue', apsTask.selectRow.APSPOOLID);
                }
            }
        });
    },
    //需显示的页面内容
    showContent: function () {
        $('#divApsEdit').show();
        $('#popApsTaskSave').show();
        $('#divAutoStartEdit').hide();
        $('#popAutoStartTaskSave').hide();
        $('#divAutoTryApsEdit').hide(); //自动排产任务选项隐藏
        $('#popTryApsTaskSave').hide(); //预排产保存按钮隐藏
        $('#divShipRevEdit').hide(); //自动转工排产接收任务选项隐藏
        $('#popShipApsTaskSave').hide(); //自动转工排产接收按钮隐藏
    },
    //绑定页面事件
    bind: function () {
        //保存
        $("#popApsTaskSave").on("click", function () {
            clearMessage();
            apsTask.saveApsScheduledTask();
        });
    },
    //保存自动排产任务定时任务信息
    saveApsScheduledTask: function () {
        //        var popupData = $("#dg").dialog('options').popupData;
        var param = {
            action: "saveApsScheduledTask",
            scheduledtaskid: apsTask.selectRow == null ? '' : apsTask.selectRow.SCHEDULEDTASKID,
            apspoolid: $("#popddlApsPool").combobox('getValue'),
            taskname: $("#popddlTaskName").combobox('getText'),
            taskstarttime: $('#poptxtStartDate').datetimebox('getValue'),
            taskendtime: $('#poptxtEndDate').datetimebox('getValue'),
            taskdesc: $("#poptxtTaskDesc").textbox('getValue'),
            cycletime: $("#txtCycle").numberbox('getValue'),
            isCalPriority: $("#cxIsCalPriority").checkbox('options').checked == true ? 1 : 0,
            isApsToEmp: $("#cxIsApsToEmp").checkbox('options').checked == true ? 1 : 0,
            factoryId: $("#ddlFactory").combobox('getValue'),
            taskType: $("#popddlTaskName").combobox('getValue')
        }
        if (isNullOrWhiteSpaceStr(param.apspoolid) || isNullOrWhiteSpaceStr(param.taskname) || isNullOrWhiteSpaceStr(param.cycletime) ||
                isNullOrWhiteSpaceStr(param.taskstarttime) || isNullOrWhiteSpaceStr(param.taskendtime)) {
            displayMessage("请输入必填项", false);
            return;
        }
        if (dayjs(param.taskendtime) < dayjs(param.taskstarttime)) {
            displayMessage("开始时间不能大于结束时间", false);
            return;
        }
        //console.log(param);
        //开始请求后台
        //提交保存
        page.post(page.ajaxUrl, param, true, function (result) {
            if (result.Result) {
                $("#dg").dialog('options').returnData = result
                $('#dg').dialog('close');
            }
            displayMessage(result.Message, result.Result);
        });
    }
};

/*
----自动开卡任务弹窗对象 add by zhangrj 20231031
*/
var autoStartTask = {
    selectData: null,
    //初始化弹窗页面
    initForm: function (popupData) {
        autoStartTask.selectData = popupData.selectRow;
        autoStartTask.showContent(); //显示页面内容
        autoStartTask.bind();
        if (autoStartTask.selectData !== null) {
            page.post(page.ajaxUrl, { action: "GetScheduledTaskDetailData", taskType: autoStartTask.selectData.TASKTYPE, scheduledTaskId: autoStartTask.selectData.SCHEDULEDTASKID }, false, function (result) {
                if (result.Result) {
                    //基础配置赋值
                    $("#popddlTaskName").combobox('setValue', autoStartTask.selectData.TASKTYPE);
                    $("#poptxtStartDate").datetimebox('setValue', autoStartTask.selectData.TASKSTARTTIME);
                    $("#poptxtEndDate").datetimebox('setValue', autoStartTask.selectData.TASKENDTIME);
                    $("#poptxtTaskDesc").textbox('setValue', autoStartTask.selectData.TASKDESC);
                    $("#txtCycle").numberbox('setValue', autoStartTask.selectData.CYCLETIME);
                    //任务选项
                    //                    autoStartTask.selectData.FACTORYRANGE = result.DBTable[0].FACTORYRANGE; //分厂范围
                    //                    autoStartTask.selectData.REFERTYPE = result.DBTable[0].REFERTYPE; //参考类型
                    //                    $("#batchProcessRule").textbox("setValue", result.DBTable[0].BATCHPROCESSRULE); //批量开卡规则
                    //                    $("#singleCardRule1").textbox("setValue", result.DBTable[0].SINGLECARDRULE1); //单件单卡开卡规则1
                    //                    $("#singleCardRule2").textbox("setValue", result.DBTable[0].SINGLECARDRULE2); //单件单卡开卡规则2
                    //                    $("#batchChildRule1").textbox("setValue", result.DBTable[0].BATCHCHILDRULE1); //批量带子序号开卡规则1
                    //                    $("#batchChildRule2").textbox("setValue", result.DBTable[0].BATCHCHILDRULE2); //批量带子序号开卡规则2
                } else {
                    displayMessage(result.Message, false);
                    $('#dg').dialog('close');
                    return;
                }
            }, function () {
                $('#dg').dialog('close');
                return;
            });
        } else {
            $("#popddlTaskName").combobox('setValue', '2'); //默认自动开卡
            $("#poptxtTaskDesc").textbox('setValue', '');
        }
        $("#poptxtFactory").textbox('setValue', $("#ddlFactory").combobox('getText'));
        //        //初始化分厂范围
        //        $("#asFactoryRange").tagbox({
        //            hasDownArrow: true,
        //            url: page.commonUrl + "?action=getFactory",
        //            valueField: 'FACTORYID',
        //            textField: 'FACTORYNAME',
        //            onLoadSuccess: function () {
        //                if (autoStartTask.selectData != null) {
        //                    $(this).tagbox('setValues', autoStartTask.selectData.FACTORYRANGE);
        //                }
        //            }
        //        });
        //        //初始化参考类型
        //        $("#asReferType").tagbox({
        //            hasDownArrow: true,
        //            data: [{ "text": "分厂订单", "value": "1" }, { "text": "转工计划", "value": "2"}],
        //            valueField: 'value',
        //            textField: 'text',
        //            onLoadSuccess: function () {
        //                if (autoStartTask.selectData != null) {
        //                    $(this).tagbox('setValues', autoStartTask.selectData.REFERTYPE);
        //                }
        //            }
        //        });
    },
    //需显示的页面内容
    showContent: function () {
        $('#divApsEdit').hide();
        $('#popApsTaskSave').hide();
        $('#divAutoStartEdit').show();
        $('#popAutoStartTaskSave').show();
        $('#divAutoTryApsEdit').hide(); //自动排产任务选项隐藏
        $('#popTryApsTaskSave').hide(); //预排产保存按钮隐藏
        $('#divShipRevEdit').hide(); //自动转工排产接收任务选项隐藏
        $('#popShipApsTaskSave').hide(); //自动转工排产接收按钮隐藏
    },
    //绑定页面事件
    bind: function () {
        //保存
        $("#popAutoStartTaskSave").on("click", function () {
            autoStartTask.save();
        });
    },
    //保存自动开卡任务
    save: function () {
        var vaild = $('#dgBaseForm').form('validate');
        if (vaild === false) {
            displayMessage("请填写必填项", false);
            return;
        }
        //        var vaild1 = $('#dgAutoStartForm').form('validate');
        //        if (vaild1 === false) {
        //            displayMessage("请填写必填项", false);
        //            return;
        //        }
        var params = {
            action: "SaveScheduledTaskData",
            scheduledTaskId: autoStartTask.selectData == null ? '' : autoStartTask.selectData.SCHEDULEDTASKID,
            taskName: $("#popddlTaskName").combobox("getText"),
            taskType: $("#popddlTaskName").combobox("getValue")
        }
        //获取基础配置里的数据
        var dgBaseFormData = $("#dgBaseForm").serializeArray();
        $.each(dgBaseFormData, function () {
            params[this.name] = this.value;
        });
        if (dayjs(params.taskEndDate) < dayjs(params.taskStartDate)) {
            displayMessage("开始时间不能大于结束时间", false);
            return;
        }
        //获取任务选项里的数据
        //        var dgAutoStartFormData = $("#dgAutoStartForm").serializeArray();
        //        $.each(dgAutoStartFormData, function () {
        //            if (params[this.name] !== undefined) {
        //                params[this.name] += "," + this.value;
        //            } else {
        //                params[this.name] = this.value;
        //            }
        //        });
        //        if (dayjs(params.taskStartDate) > dayjs(params.taskEndDate)) {
        //            displayMessage("开始时间不能大于结束时间", false);
        //            return;
        //        }
        //提交保存
        page.post(page.ajaxUrl, params, true, function (result) {
            if (result.Result) {
                $("#dg").dialog('options').returnData = result
                $('#dg').dialog('close');
            }
            displayMessage(result.Message, result.Result);
        });
    }
};


/*
----预排产任务弹窗对象 add by zhangrj 20250114
*/
var tryApsTask = {
    selectData: null,
    //初始化弹窗页面
    initForm: function (popupData) {
        tryApsTask.selectData = popupData.selectRow;
        tryApsTask.showContent(); //显示页面内容
        tryApsTask.bind();
        var apsPoolId = "";
        if (tryApsTask.selectData !== null) {
            page.post(page.ajaxUrl, { action: "GetScheduledTaskDetailData", taskType: tryApsTask.selectData.TASKTYPE, scheduledTaskId: tryApsTask.selectData.SCHEDULEDTASKID }, false, function (result) {
                if (result.Result) {
                    //基础配置赋值
                    $("#popddlTaskName").combobox('setValue', tryApsTask.selectData.TASKTYPE);
                    $("#poptxtStartDate").datetimebox('setValue', tryApsTask.selectData.TASKSTARTTIME);
                    $("#poptxtEndDate").datetimebox('setValue', tryApsTask.selectData.TASKENDTIME);
                    $("#poptxtTaskDesc").textbox('setValue', tryApsTask.selectData.TASKDESC);
                    $("#txtCycle").numberbox('setValue', tryApsTask.selectData.CYCLETIME);
                    apsPoolId = result.DBTable[0].APSPOOLID;
                } else {
                    displayMessage(result.Message, false);
                    $('#dg').dialog('close');
                    return;
                }
            }, function () {
                $('#dg').dialog('close');
                return;
            });
        } else {
            $("#popddlTaskName").combobox('setValue', '8'); //默认预排产
            $("#poptxtTaskDesc").textbox('setValue', '');
        }
        $("#poptxtFactory").textbox('setValue', $("#ddlFactory").combobox('getText'));
        $('#popddlTryApsPool').combobox({
            url: page.ajaxUrl + "?action=getPoolList&factoryId=" + popupData.factoryId,
            valueField: 'APSPOOLID',
            textField: 'APSPOOLNAME',
            onLoadSuccess: function () {
                if (apsPoolId !== "") {
                    $(this).combobox('setValue', apsPoolId);
                }
            }
        });
    },
    //需显示的页面内容
    showContent: function () {
        $('#divApsEdit').hide(); //自动排产任务选项隐藏
        $('#popApsTaskSave').hide(); //自动排产保存按钮隐藏
        $('#divAutoStartEdit').hide(); //自动开卡任务选项隐藏
        $('#popAutoStartTaskSave').hide(); //自动开卡保存按钮隐藏
        $('#divAutoTryApsEdit').show(); //自动排产任务选项显示
        $('#popTryApsTaskSave').show(); //预排产保存按钮显示
        $('#divShipRevEdit').hide(); //自动转工排产接收任务选项隐藏
        $('#popShipApsTaskSave').hide(); //自动转工排产接收按钮隐藏
    },
    //绑定页面事件
    bind: function () {
        //保存
        $("#popTryApsTaskSave").on("click", function () {
            tryApsTask.save();
        });
    },
    //保存自动开卡任务
    save: function () {
        var vaild = $('#dgBaseForm').form('validate');
        if (vaild === false) {
            displayMessage("请填写必填项", false);
            return;
        }
        var params = {
            action: "SaveScheduledTaskData",
            scheduledTaskId: tryApsTask.selectData == null ? '' : tryApsTask.selectData.SCHEDULEDTASKID,
            taskName: $("#popddlTaskName").combobox("getText"),
            taskType: $("#popddlTaskName").combobox("getValue"),
            apspoolid: $("#popddlTryApsPool").combobox('getValue')
        }
        //获取基础配置里的数据
        var dgBaseFormData = $("#dgBaseForm").serializeArray();
        $.each(dgBaseFormData, function () {
            params[this.name] = this.value;
        });
        if (dayjs(params.taskEndDate) < dayjs(params.taskStartDate)) {
            displayMessage("开始时间不能大于结束时间", false);
            return;
        }
        //提交保存
        page.post(page.ajaxUrl, params, true, function (result) {
            if (result.Result) {
                $("#dg").dialog('options').returnData = result
                $('#dg').dialog('close');
            }
            displayMessage(result.Message, result.Result);
        });
    }
};


/*
----自动排产转工接收任务弹窗对象 add by zhangrj 20251106
*/
var shipApsRecTask = {
    selectData: null,
    //初始化弹窗页面
    initForm: function (popupData) {
        shipApsRecTask.selectData = popupData.selectRow;
        shipApsRecTask.showContent(); //显示页面内容
        shipApsRecTask.bind();
        if (shipApsRecTask.selectData !== null) {
            page.post(page.ajaxUrl, { action: "GetScheduledTaskDetailData", taskType: shipApsRecTask.selectData.TASKTYPE, scheduledTaskId: shipApsRecTask.selectData.SCHEDULEDTASKID }, false, function (result) {
                if (result.Result) {
                    //基础配置赋值
                    $("#popddlTaskName").combobox('setValue', shipApsRecTask.selectData.TASKTYPE);
                    $("#poptxtStartDate").datetimebox('setValue', shipApsRecTask.selectData.TASKSTARTTIME);
                    $("#poptxtEndDate").datetimebox('setValue', shipApsRecTask.selectData.TASKENDTIME);
                    $("#poptxtTaskDesc").textbox('setValue', shipApsRecTask.selectData.TASKDESC);
                    $("#txtCycle").numberbox('setValue', shipApsRecTask.selectData.CYCLETIME);
                    $("#asReceiveRefer").combobox('setValue', result.DBTable[0].RECEIVEREFER);
                    $("#asRevCoverCycle").numberbox('setValue', result.DBTable[0].REVCOVERCYCLE);
                } else {
                    displayMessage(result.Message, false);
                    $('#dg').dialog('close');
                    return;
                }
            }, function () {
                $('#dg').dialog('close');
                return;
            });
        } else {
            $("#popddlTaskName").combobox('setValue', '9'); //默认自动转工排产接收
            $("#poptxtTaskDesc").textbox('clear');
            $("#asReceiveRefer").combobox('clear');
            $("#asRevCoverCycle").numberbox('clear');
        }
        $("#poptxtFactory").textbox('setValue', $("#ddlFactory").combobox('getText'));
    },
    //需显示的页面内容
    showContent: function () {
        $('#divApsEdit').hide(); //自动排产任务选项隐藏
        $('#popApsTaskSave').hide(); //自动排产保存按钮隐藏
        $('#divAutoStartEdit').hide(); //自动开卡任务选项隐藏
        $('#popAutoStartTaskSave').hide(); //自动开卡保存按钮隐藏
        $('#divAutoTryApsEdit').hide(); //自动排产任务选项隐藏
        $('#popTryApsTaskSave').hide(); //预排产保存按钮隐藏
        $('#divShipRevEdit').show(); //自动转工排产接收任务选项显示
        $('#popShipApsTaskSave').show(); //自动转工排产接收按钮显示
    },
    //绑定页面事件
    bind: function () {
        //保存
        $("#popShipApsTaskSave").on("click", function () {
            shipApsRecTask.save();
        });
    },
    //保存自动开卡任务
    save: function () {
        var vaild = $('#dgBaseForm').form('validate');
        if (vaild === false) {
            displayMessage("请填写必填项", false);
            return;
        }
        var params = {
            action: "SaveScheduledTaskData",
            scheduledTaskId: shipApsRecTask.selectData == null ? '' : shipApsRecTask.selectData.SCHEDULEDTASKID,
            taskName: $("#popddlTaskName").combobox("getText"),
            taskType: $("#popddlTaskName").combobox("getValue")
        }
        //获取基础配置里的数据
        var dgBaseFormData = $("#dgBaseForm").serializeArray();
        $.each(dgBaseFormData, function () {
            params[this.name] = this.value;
        });
        //获取任务配置里的数据
        var dgShipRevFormData = $("#dgShipRevForm").serializeArray();
        $.each(dgShipRevFormData, function () {
            params[this.name] = this.value;
        });
        if (dayjs(params.taskEndDate) < dayjs(params.taskStartDate)) {
            displayMessage("开始时间不能大于结束时间", false);
            return;
        }
        //提交保存
        page.post(page.ajaxUrl, params, true, function (result) {
            if (result.Result) {
                $("#dg").dialog('options').returnData = result
                $('#dg').dialog('close');
            }
            displayMessage(result.Message, result.Result);
        });
    }
};
$(function () {
    page.init();
});